//
//  LBDelegateCenter.m
//  TEXT
//
//  Created by mac on 2025/3/2.
//  Copyright © 2025 刘博. All rights reserved.
//

#import "LBDelegateCenter.h"

@implementation LBDelegateCenter

- (instancetype)initWithTarget:(id)target proxy:(id)proxy
{
    if (self = [super init]) {
        _target = target ? target : [NSNull null];
        _proxy = proxy ? proxy : [NSNull null];
    }
    
    return self;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    NSMethodSignature *targetSign = [_target methodSignatureForSelector:sel];
    if (targetSign) {
        return targetSign;
    }

    NSMethodSignature *proxySign = [_proxy methodSignatureForSelector:sel];
    if (proxySign) {
        return proxySign;
    }
    
    return [super methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    //AUKLogInfo(@"New proxy = %@, selector=%@", [self.proxy class], NSStringFromSelector([anInvocation selector]));
    
    BOOL hit = NO;
    if ([_target respondsToSelector:[anInvocation selector]]) {
        hit = YES;
        [anInvocation invokeWithTarget:_target];
    }
    
    if ([_proxy respondsToSelector:[anInvocation selector]]) {
        //AUKLogInfo(@"New proxy handle");
        hit = YES;
        [anInvocation invokeWithTarget:_proxy];
    }
    
    if (!hit && [super respondsToSelector:[anInvocation selector]]) {
        [super forwardInvocation:anInvocation];
    }
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
    if ([_target respondsToSelector:aSelector]) {
        return YES;
    }
    if ([_proxy respondsToSelector:aSelector]) {
        return YES;
    }
    
    return [super respondsToSelector:aSelector];
}

- (BOOL)conformsToProtocol:(Protocol *)aProtocol
{
    if ([_target conformsToProtocol:aProtocol]) {
        return YES;
    }
    if ([_proxy conformsToProtocol:aProtocol]) {
        return YES;
    }
    
    return [super conformsToProtocol:aProtocol];
}

- (BOOL)isKindOfClass:(Class)aClass
{
    if ([_target isKindOfClass:aClass]) {
        return YES;
    }
    if ([_proxy isKindOfClass:aClass]) {
        return YES;
    }
    
    return [super isKindOfClass:aClass];
}

- (BOOL)isMemberOfClass:(Class)aClass
{
    if ([_target isMemberOfClass:aClass]) {
        return YES;
    }
    if ([_proxy isMemberOfClass:aClass]) {
        return YES;
    }
    
    return [super isMemberOfClass:aClass];
}

@end
